/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.scene.domain.DamageExamination;
import com.koron.scene.service.api.DamageExaminationService;
import com.koron.scene.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "damageExamination", description = "危害因素检测接口")
@RestController
@RequestMapping("/damageExamination")
public class DamageExaminationController {

    private final static  Logger logger = LoggerFactory.getLogger(DamageExaminationController.class);

    @Autowired
    private DamageExaminationService examinationService;

    @ApiOperation("存储危害因素检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "检测名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsibleDeptCode", value = "责任单位code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsibleDeptName", value = "责任单位名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "examinationTime", value = "检测时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "检测内容", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "defect", value = "缺陷", required = true, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "rectification", value = "整改" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "上传的附件" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFileAddress", value = "删除的附件" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepFileAddress", value = "保留的附件" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delPreFileAddress", value = "删除的预览附件" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepPreFileAddress", value = "保留的预览附件" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/save.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改危害因素检测",businessModule = "危害因素检测", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Boolean> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String id, @RequestParam String corpCode,
                                     @RequestParam String name, @RequestParam(required = false)  String code, @RequestParam String responsibleDeptCode, @RequestParam String responsibleDeptName,
                                     @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date examinationTime,
                                     @RequestParam String content, @RequestParam String defect, @RequestParam(required = false) String rectification,
                                     @RequestParam(required = false) final MultipartFile[] files, @RequestParam(required = false) final String delFileAddress,
                                     @RequestParam(required = false) final String keepFileAddress, @RequestParam(required = false) String delPreFileAddress,
                                     @RequestParam(required = false) String keepPreFileAddress) {
        if (user == null) {
            return MessageBean.create(BusinessCode.NO_LOGIN.getCode(), BusinessCode.NO_LOGIN.getDescription(), Boolean.class);
        }
        DamageExamination examination = new DamageExamination(user.getCode(), user.getName());
        examination.setId(id);
        examination.setCorpCode(corpCode);
        examination.setName(name);
        examination.setCode(code);
        examination.setResponsibleDeptCode(responsibleDeptCode);
        examination.setResponsibleDeptName(responsibleDeptName);
        examination.setExaminationTime(examinationTime);
        examination.setContent(content);
        examination.setDefect(defect);
        examination.setRectification(rectification);
        if (StringUtils.isBlank(examination.getCorpCode()) || StringUtils.isBlank(examination.getName()) || StringUtils.isBlank(examination.getContent())) {
            return MessageBean.create(BusinessCode.INSUFFICIENT_PARAM.getCode(), BusinessCode.INSUFFICIENT_PARAM.getDescription(), Boolean.class);
        }
        Integer result = examinationService.persist(examination, files, delFileAddress, keepFileAddress, delPreFileAddress, keepPreFileAddress);
        BusinessCode bc = BusinessCode.valueOf(result);
        return MessageBean.create(bc.getCode(), bc.getDescription(), Boolean.class);
    }


    @ApiOperation("批量删除危害因素检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "设备Id,多个之间用逗号分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    @Log(title = "批量删除危害因素检测",businessModule = "危害因素检测", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Boolean> batchDelete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (user == null) {
            return MessageBean.create(BusinessCode.NO_LOGIN.getCode(), BusinessCode.NO_LOGIN.getDescription(), Boolean.class);
        }
        MessageBean<Boolean> msg = new MessageBean<>();
        if (StringUtils.isEmpty(ids)) {
            return MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Boolean.class);
        }
        try {
            String[] idArray = ids.split("[,，]");
            msg.setData(examinationService.batchDetele(Arrays.asList(idArray)));
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setCode(BusinessCode.SUCCESS.getCode());
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }


    @ApiOperation("查询危害因素检测列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "检测名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsibleDeptName", value = "责任部门" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "beginTime", value = "开始日期" , dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束日期" , dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<DamageExamination>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam(required = false) String name,
                                                         @RequestParam(required = false) String responsibleDeptName, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginTime,
                                                         @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "15") Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<DamageExamination>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NO_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<DamageExamination>> msg = new MessageBean<>();
        Integer start = (page <= 1) ? 0 : (page - 1) * pageSize;
        try {
            DataBean<DamageExamination> dataBean = examinationService.fetchExaminations(corpCode, name, responsibleDeptName, beginTime, endTime, start, pageSize);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("危害因素检测详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危害因素检测Id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/detail.htm", method = RequestMethod.POST)
    public MessageBean<DamageExamination> detail(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        if (null == user) {
            MessageBean<DamageExamination> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NO_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DamageExamination> msg = new MessageBean<>();
        try {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            msg.setData(examinationService.fetchOne(id));
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
            msg.setCode(BusinessCode.SUCCESS.getCode());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }


    @ApiOperation("危害因素检测列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "检测名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsibleDeptName", value = "责任部门" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "beginTime", value = "开始日期" , dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束日期" , dataType = "date", paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = RequestMethod.GET)
    public HttpEntity<?> export(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) String corpCode, @RequestParam(required = false) String name,
                                @RequestParam(required = false) String responsibleDeptName, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginTime,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        if (null == user) {
            return null;
        }
        List<DamageExamination> list = examinationService.exportList(user, corpCode, name,responsibleDeptName,beginTime,endTime);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/damageExamination.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/damageExamination.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("危害因素检测列表", targetFile, "damageExamination.btl", map);
    }
}
